package com.kayak.core;

import org.apache.commons.lang.StringUtils;

import com.kayak.enums.Dialect;
import com.kayak.pojo.ColumnObj;


public class Sql {

    /**
     * 长度
     */
    private int length;
    /**
     * 字段名
     */
    private String field;
    /**
     * 数据库方言
     */
    private Dialect dialect;
    /**
     * 是否可以为空
     */
    private boolean isEmpty;
    /**
     * 字段类型
     */
    private FieldType fieldType;

    private String isEmptySql;
    
    public Sql(ColumnObj columnObj,Dialect dialect){
    	 this.dialect = dialect;
         this.field = columnObj.getFieldName();
         this.isEmpty = columnObj.getIsEmpty();
         this.length = StringUtils.isBlank(columnObj.getLength()) ? 32 : Integer.parseInt(columnObj.getLength());
         this.fieldType = FieldType.init(columnObj.getFieldType());
         this.isEmptySql = isEmpty ? "" : "NOT NULL";  
    }
    
    public String getSql(){
    	return sql();
    }
    
    private String sql(){
    	 if(FieldType.CHAR == fieldType){
             return charType();
         }
         if(FieldType.VARCHAR == fieldType){
             return varchar();
         }
         if(FieldType.DECIMAL == fieldType){
             return decimalType();
         }
         return null;
    }
    private String charType(){
        if(dialect == Dialect.MYSQL){
                return field + " char("+length+") " + isEmptySql;
        }
        return "";
    }

    private String varchar(){
        if(dialect == Dialect.MYSQL){
        	return field + " varchar("+length+") " + isEmptySql;
        }
        return "";
    }

    private String decimalType(){
        if(dialect == Dialect.MYSQL){
        	  return field + " decimal(" + length + ") " + isEmptySql;
        }
        return "";
    }
    public enum FieldType {
        DECIMAL,
        VARCHAR, 
        CHAR;

        public static FieldType init(String key){
            if(StringUtils.isBlank(key)) return null;
            for(FieldType fieldType : FieldType.values()){
                if(String.valueOf(fieldType).equalsIgnoreCase(key))
                    return fieldType;
            }
            return null;
        }

    }
}
